package com.my.socket.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * User: Alex Zhong
 * Date: 2016/6/17
 */
public class AcceptCallable implements Callable<Void> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AcceptCallable.class);

    private ServerSocket serverSocket;

    public AcceptCallable(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public Void call() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();

        while (true) {
            LOGGER.info("waiting for the client connection in thread {}", Thread.currentThread().getId());
            Socket socket = serverSocket.accept();
            LOGGER.info("assign a connection from the client {} in thread {}", socket.getPort(), Thread.currentThread().getId());

            HandleCallable handleCallable = new HandleCallable(socket);
            executorService.submit(handleCallable);
        }

//        socket.close();
//        serverSocket.close();
    }
}
